/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.metadata;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Martin Rehanek, Martin.Rehanek@gmail.com
 */
public class MultipleDataField {

    List<DataField> dataFields;

    public MultipleDataField(int initialCapacity) {
        dataFields = new ArrayList<DataField>(initialCapacity);
    }

    public void addDataField(DataField datafield) {
        dataFields.add(datafield);
    }

    /**
     *
     * @param code
     * @return List of contents of subfields with code from all datafields
     */
    public List<String> getSubfieldContents(char code) {
        List<String> subfields = new ArrayList<String>();
        for (DataField datafield : dataFields) {
            String subfield = datafield.getSubfield(code);
            if (subfield != null) {
                subfields.add(subfield);
            }
        }
        return subfields;
    }

    public String subfieldsToString(char code) {
        List<String> subfields = getSubfieldContents(code);
        StringBuilder builder = new StringBuilder(2);
        for (int i = 0; i < subfields.size(); i++) {
            builder.append(subfields.get(i));
            if (i != subfields.size() - 1) {
                builder.append(':');
            }
        }
        return builder.toString();
    }

    /**
     *
     * @param subfieldCode
     * @param value
     * @return true if there exist a subfield (in one of datafields), content of which equals $value
     * (it is case in sensitive)
     */
    public boolean contains(char subfieldCode, String value) {
        String val = value.toLowerCase();
        List<String> contents = getSubfieldContents(subfieldCode);
        for (String content : contents) {
            if (content.toLowerCase().equals(val)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Returns true if there exists at least one datafield with its subfield $subfieldCode containing $value
     * @param value Value of the subfield $code we are looking for
     * @param subfieldCode Code of the subfield
     * @return
     */
    public boolean subfieldsContain(char subfieldCode, String value) {
        List<String> subfields = getSubfieldContents(subfieldCode);
        for (String subfield : subfields) {
            if (value.equals(subfield)) {
                return true;
            }
        }
        return false;
    }

    public int size() {
        return dataFields.size();
    }

    public boolean empty() {
        return 0 == size();
    }
}
